import 'dart:async';

import 'package:chat_app_project/components/primary_button.dart';
import 'package:chat_app_project/const/sys_const.dart';
import 'package:chat_app_project/constants.dart';
import 'package:chat_app_project/dao/login_dao.dart';
import 'package:chat_app_project/models/const.dart';
import 'package:chat_app_project/models/user_login_info_entity.dart';
import 'package:chat_app_project/util/sp_util.dart';
import 'package:chat_app_project/util/toast_util.dart';
import 'package:flutter/material.dart';
import 'package:getwidget/components/text_field/gf_text_field.dart';
import 'package:package_info/package_info.dart';

import '../../config/const.dart';
import '../../tool/event_bus.dart';
import '../../tool/im.dart';
import '../home.dart';

class LoginPage extends StatefulWidget {
  const LoginPage({Key? key}) : super(key: key);

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  String _phoneNumber = '18001759732';
  String _verificationCode = '1234';
  bool _isVerificationCodeButtonEnabled = true;
  String _timerCountdown = "获取验证码";
  final TextEditingController _phoneController = TextEditingController();
  final TextEditingController _codeController = TextEditingController();

  @override
  void initState() {
    super.initState();
    setState(() {
      //默认值 先测试
      _phoneController.value = TextEditingValue(text: _phoneNumber);
      _codeController.value = TextEditingValue(text: _verificationCode);
    });
  }

  void _handlePhoneNumberChanged(String value) {
    setState(() {
      _phoneNumber = value;
    });
  }

  void _handleVerificationCodeChanged(String value) {
    setState(() {
      _verificationCode = value;
    });
  }

  void _handleVerificationCodeButtonPressed() {
    setState(() {
      _isVerificationCodeButtonEnabled = false;
      _timerCountdown = "60";
      _startTimer();
    });
  }

  void _startTimer() {
    Timer.periodic(const Duration(seconds: 1), (Timer timer) {
      setState(() {
        int c = int.parse(_timerCountdown);
        if (c > 0) {
          _timerCountdown = (c - 1).toString();
        } else {
          timer.cancel();
          _isVerificationCodeButtonEnabled = true;
          _timerCountdown = "获取验证码";
        }
      });
    });
  }

  static Future<String> getAppInfo() async {
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    String appName = packageInfo.appName;
    String packageName = packageInfo.packageName;
    String version = packageInfo.version;
    String buildNumber = packageInfo.buildNumber;
    debugPrint(
        "_appName=$appName   _packageName=$packageName    _version=$version");
    return appName + packageName + version + buildNumber;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: SafeArea(
            child: Padding(
      padding: const EdgeInsets.symmetric(horizontal: kDefaultPadding),
      child: Column(
        children: [
          const Spacer(flex: 1),
          ClipOval(
              child: Image.network(
            SysConst.defaultAvatar,
            fit: BoxFit.cover,
            height: 146,
          )),
          const Spacer(),
          GFTextField(
            controller: _phoneController,
            // title: "手机号",
            // hint: "请输入手机号",
            onChanged: _handlePhoneNumberChanged,
          ),
          const SizedBox(height: 10), // 文字和按钮之间的间距
          Row(
            children: [
              Expanded(
                  child: GFTextField(
                controller: _codeController,
                // title: "验证码",
                // hint: "请输入验证码",
                onChanged: _handleVerificationCodeChanged,
              )),
              SizedBox(
                height: 40,
                child: ElevatedButton(
                  onPressed: _isVerificationCodeButtonEnabled
                      ? () => _handleVerificationCodeButtonPressed()
                      : null,
                  child: Text(_timerCountdown),
                ),
              ),
            ],
          ),
          const Spacer(),
          PrimaryButton(
            text: '登录',
            press: () async {
              if (_phoneNumber.isEmpty || _verificationCode.isEmpty) {
                ToastUtil.toast("请输入完整信息");
                return;
              }
              if (_phoneNumber.length != 11) {
                ToastUtil.toast("请输入正确的手机号");
                return;
              }
              //appVersion,
              //     channel,
              //     phone, {
              //     verifyCode,
              //     wxCode,
              PackageInfo packageInfo = await PackageInfo.fromPlatform();
              Map<String, dynamic> params = {
                "phone": _phoneNumber,
                "verifyCode": _verificationCode,
                "appVersion": packageInfo.version,
                "channel": "flutter",
              };
              LoginDao.loginByPhone(params).then((value) {
                UserLoginInfoEntity loginInfo =
                    UserLoginInfoEntity.fromJson(value.data);
                UserInfo.login(pre: () {
                  SpUtil.putString("id", loginInfo.id.toString());
                  SpUtil.putString("token", loginInfo.tokenVo!.loginToken);
                  SpUtil.putObject("loginInfo", loginInfo);
                });

                ToastUtil.toast("登录成功");
                // ImService.tryConnect();
                bus.emit(TP_PROFILE_UPDATE);

                IMUtils.initIM().then((result) {
                  if (result) {
                    Navigator.pushAndRemoveUntil(
                        context,
                        MaterialPageRoute(
                            builder: (_) => HomeScreen(
                                  selectedIndex: 0,
                                )),
                        // builder: (_) => JoinChannelAudio()),
                        (route) => false);
                  }
                });
                // Navigator.push(context, MaterialPageRoute(builder: (context) => const ChatsScreen()));
              });
            },
          ),
          // const SizedBox(height: kDefaultPadding * 1.5),
          // PrimaryButton(
          //   color: Theme.of(context).colorScheme.secondary,
          //   text: 'Sign Up',
          //   press: () {},
          // ),
          const Spacer(flex: 2),
        ],
      ),
    )));
  }
}
